package com.hzz.framework.filter;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "crossFilter", urlPatterns = {"/boss/*", "/api/*", "/file/*"})
@Slf4j
@Order(-9999)
public class CrossFilter implements Filter {
    @Value("${cross.origin:*}")
    private String accessControlAllowOrigin;
    @Value("${cross.methods}")
    private String accessControlAllowMethods;
    @Value("${cross.headers}")
    private String accessControlAllowHeaders;

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("===============设置“跨域”访问头=============");
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (response instanceof HttpServletResponse) {
            HttpServletRequest servletRequest = ((HttpServletRequest) request);
            HttpServletResponse servletResponse = ((HttpServletResponse) response);
            addHeadersFor200Response(servletRequest, servletResponse);
            // 如果是OPTIONS则结束请求
            if (HttpMethod.OPTIONS.toString().equals(servletRequest.getMethod())) {
                servletResponse.setStatus(HttpStatus.NO_CONTENT.value());
                return;
            }
            chain.doFilter(request, response);
        }
    }

    private void addHeadersFor200Response(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", accessControlAllowOrigin);
        response.addHeader("Access-Control-Allow-Methods", accessControlAllowMethods);
        response.setHeader("Access-Control-Allow-Headers", accessControlAllowHeaders);
    }
}